<?php
  require(dirname(__FILE__) . '/includes/init.php');
  if ($_REQUEST['act'] == 'read'){
	$sql = "select insert_time from ".$ecs->table('search_orders')." where order_id = (select max(order_id) from ".$ecs->table('search_orders').")";
    $inert_time = $db->getOne($sql);
	if(gmtime()-$inert_time<=24*3600){
		$dao_str = "今天您已经导入过数据了";
	}else{
	require_once('includes/cls_readexcel.php'); 
	$data= new Spreadsheet_Excel_Reader(); 
	$data->setOutputEncoding('utf-8'); 
		if ($_FILES["file"]["error"] > 0)
		{
			$error = urlencode('文件出错了，错误码：'.$_FILES["file"]["error"]);
			header("Location: search_orders.php?error=$error\n");exit;
		}else if(end(explode(".",strtolower($_FILES["file"]['name'])))!='xls'){
			$error = urlencode('请选择excel文件');
			header("Location: search_orders.php?error=$error\n");exit;
		}
		else
		{
			$datapath = $_FILES["file"]["tmp_name"];
		}
		$data->read($datapath);
		$count = 0;
		$ok = false;
		for($i= 2; $i<= $data->sheets[0]['numRows']; $i++){
			/*if($data->sheets[0]['cells'][$i][4]&&!$data->sheets[0]['cells'][$i][2]){
				$order = $db->getRow("select * from ".$ecs->table('search_orders')." where order_id =  (select max(order_id) from ".$ecs->table('search_orders').")");
				$sql = "INSERT INTO " .$ecs->table('search_orders')." (order_sn,user_name,mobile,products_name,money,order_time,insert_time) values('".$order['order_sn']."','".$order['user_name']."','".$order['mobile']."','".$data->sheets[0]['cells'][$i][4]."','".$order['money']."','".$order['order_time']."','".time()."')";
				$ok = $db->query($sql);
				if($ok){
					$count++;
				}
			}else{*/
			   $order_time = substr($data->sheets[0]['cells'][$i][11],4,20);
			   $order_time = strtotime($order_time);
			   $sql = "INSERT INTO " .$ecs->table('search_orders')." (order_sn,user_name,mobile,products_name,money,order_time,insert_time) values('".$data->sheets[0]['cells'][$i][1]."','".$data->sheets[0]['cells'][$i][3]."','".$data->sheets[0]['cells'][$i][6]."','".$data->sheets[0]['cells'][$i][5]."','".$data->sheets[0]['cells'][$i][4]."','".$order_time."','".time()."')";
				$ok = $db->query($sql);
				if($ok){
					++$count;
				}
			//}
		}
		$dao_str = '已成功导入'.$count.'条';
	}
}else if($_REQUEST['act'] == 'search'){
    $start_time = strtotime($_REQUEST['start_time']);
	$end_time = strtotime($_REQUEST['end_time']);
    $sql = "select * from ".$ecs->table('search_orders')." where order_time between ".$start_time." and ".$end_time." and products_name like '%".$_REQUEST['products_name']."%'";
	$order_list = $db->getAll($sql);
	//print_r($order_list);
}else if($_REQUEST['act'] == 'download'){
	/*$filename = date('Y-m-d-His',time()).'download';
	header("Content-type: application/vnd.ms-excel; charset=utf-8");
    header("Content-Disposition: attachment; filename=$filename.xls");
	$start_time = strtotime($_REQUEST['start_time']);
	$end_time = strtotime($_REQUEST['end_time']);
	$data  = "单号\t用户名" . "\t手机\t\n";
	$order_list = $db->getAll("select * from ".$ecs->table('search_orders')." where order_time between '".$start_time."' and '".$end_time."' and products_name like '%".$_REQUEST['products_name']."%'");
	if($order_list){
		foreach($order_list as $order){
			$data  .=  $order['order_id']."\t".$order['user_name']. "\t".$order['mobile']."\t\n";
		}
	}
	$data = iconv('utf-8', 'gbk',$data);
	echo $data. "\t";
	exit;*/
	require_once('includes/cls_createexcel.php');
	//$excel = new excel();
	$filename = iconv('utf-8', 'gbk',date('Y-m-d-His',time()).'群发数据');
	excel::getInstance()->set_menu(array("单号","用户名","手机"));
    //excel::getInstance()->get_data($data); //二维数组
	$start_time = strtotime($_REQUEST['start_time']);
	$end_time = strtotime($_REQUEST['end_time']);
	
	$order_list = $db->getAll("select * from ".$ecs->table('search_orders')." where order_time between '".$start_time."' and '".$end_time."' and products_name like '%".$_REQUEST['products_name']."%'");
	/*if($order_list){
	    foreach($order_list as $order){
			excel::getInstance()->get_data($order);
		}
	}*/
	excel::getInstance()->get_data(array('344343','43344343','43433443'));
    excel::getInstance()->download($fileName);
	//exit;
}else if($_REQUEST['act'] == 'download_temp'){
	download(iconv('UTF-8','GB2312','./userUpload/templet/群发订单导入模板.xls'),iconv('UTF-8','GB2312','群发订单导入模板.xls'));
}


function download($url, $filename) {   
        // 获得文件大小, 防止超过2G的文件, 用sprintf来读
		if(file_exists($url)){
        	$filesize = sprintf ( "%u", filesize ( $url ) ); 
		}  
        if (! $filesize) {   
            return false;   
         }   
         header ( "Content-type:application/octet-stream\n" ); //application/octet-stream   
         header ( "Content-type:unknown/unknown;" );   
         header ( "Content-disposition: attachment; filename=\"" . $filename . "\"" );   
         header ( 'Content-transfer-encoding: binary' );   
        if ($range = getenv ( 'HTTP_RANGE' )) { // 当有偏移量的时候，采用206的断点续传头   
            $range = explode ( '=', $range );   
            $range = $range [1];   
               
             header ( "HTTP/1.1 206 Partial Content" );   
             header ( "Date: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );   
             header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s", filemtime ( $url ) ) . " GMT" );   
             header ( "Accept-Ranges: bytes" );   
             header ( "Content-Length:" . ($filesize - $range) );   
             header ( "Content-Range: bytes " . $range . ($filesize - 1) . "/" . $filesize );   
             header ( "Connection: close" . "\n\n" );   
         } else {   
             header ( "Content-Length:" . $filesize . "\n\n" );   
            $range = 0;   
         }   
         loadFile ( $url ); 
		 return true;  
    }   
      
    function loadFile($filename, $retbytes = true) {   
        $buffer = '';   
        $cnt = 0;   
        $handle = fopen ( $filename, 'rb' );   
        if ($handle === false) {   
            return false;   
         }   
        while ( ! feof ( $handle ) ) {   
            $buffer = fread ( $handle, 1024 * 1024 );   
            echo $buffer;   
             ob_flush ();   
            flush ();   
            if ($retbytes) {   
                $cnt += strlen ( $buffer );   
             }   
         }   
        $status = fclose ( $handle );   
        if ($retbytes && $status) {   
            return $cnt; // return num. bytes delivered like readfile() does.   
         }   
        return $status;   
    }   
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>管理中心 - 订单列表 </title>
<meta name="robots" content="noindex, nofollow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="styles/general.css" rel="stylesheet" type="text/css" />
<link href="styles/main.css" rel="stylesheet" type="text/css" />
<link href="js/calendar/calendar.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/calendar/calendar.js"></script>
</head>
<body>
 
<h1>
<span class="action-span"><a href="search_orders.php?act=download_temp" title="订单导入模板下载">订单导入模板下载</a></span>
<span class="action-span"><a href="search_orders.php?act=download&products_name=<?php echo urlencode($_POST['products_name']);?>&start_time=<?php echo $_POST['start_time'];?>&end_time=<?php echo $_POST['end_time'];?>" title="下载数据">下载群发数据</a></span>
<span class="action-span1"><a target="_top" href="index.php?act=main">管理中心</a> </span><span id="search_id" class="action-span1"> - 订单列表 </span>
<div style="clear:both"></div>
</h1>
<?php if(!empty($_GET['error'])){?>
<div class="form-div" id="error">
  <span><a href="#" onclick="javascript:err_hide()" title="关闭"><img src="images/no.gif" border="0" alt="关闭"></a><?php echo urldecode($_GET['error']); ?></span>
</div>
<?php }?>
<div class="form-div">
  <form method="post" action="search_orders.php?act=read" enctype="multipart/form-data">
   Excel<input type="file" name="file" size="50" />
   <input type="submit" name="readexcel" value="导入" class="button"/>
   <?php if($dao_str){?><span style="color:red;"><?php echo $dao_str;?></span><?php }?>
  </form>
</div>

<div class="form-div">
  <form action="search_orders.php" method="post" name="searchForm" onsubmit="return search_yz()">
    <img src="images/icon_search.gif" width="26" height="22" border="0" alt="SEARCH" />
    产品名<input name="products_name" type="text" id="products_name" size="15">
	开始时间<input type="text" name="start_time"  id="start_time" size="10" readonly="readonly"/><input name="selbtn1" type="button" id="selbtn1" onclick="return showCalendar('start_time', '%Y-%m-%d', '24', false, 'selbtn1');" value="选择" class="button"/>
	结束时间<input type="text" name="end_time"  id="end_time" size="10" readonly="readonly"/><input name="selbtn2" type="button" id="selbtn2" onclick="return showCalendar('end_time', '%Y-%m-%d', '24', false, 'selbtn2');" value="选择" class="button"/>
	<input type="hidden" name="act" value="search" />
    <input type="submit" value=" 搜索 " class="button" />
  </form>
</div>
<script type="text/javascript">
function search_yz(){
	var products_name = $("#products_name").val();
	var start_time = $("#start_time").val();
	var end_time = $("#end_time").val();
	var msg = '';
	if(products_name==""){
		msg += '请输入产品名\n';
	}
	if(start_time.length<=0){
		msg += '请选择订结束单时间\n';
	}
	if(end_time.length<=0){
		msg += '请选择订结束单时间\n';
	}
	if (msg.length > 0)
	{
		alert(msg);
		return false;
	}
	else
	{
		return true;
	}
}
</script> 
<!-- 订单列表 -->
<form method="post" action="order.php?act=operate" name="listForm" onsubmit="return check()">
  <div class="list-div" id="listDiv">
 
<table cellpadding="3" cellspacing="1">
  <tr>
    <th>订单号</th>
    <th>姓名</th>
    <th>手机号</th>
    <th>产品</th>
    <th>订单金额</th>
    <th>订单日期</th>
  <tr>
  <?php 
  if(count($order_list)>0){
	foreach($order_list AS $index => $array_val){
  ?>
   <tr>
    <td><?php echo $array_val['order_sn']?></td>
    <td><?php echo $array_val['user_name']?></td>
	<td><?php echo $array_val['mobile']?></td>
	<td><?php echo $array_val['products_name']?></td>
    <td><?php echo $array_val['money']?></td>
    <td><?php echo date('Y-m-d H:i:s',$array_val['order_time']);?></td>
  <tr>
  <?php 
      } 
	}
  ?>
  </table>
 
<!-- 分页 -->
  </div>
 
</form>
<script type="text/javascript">
function err_hide(){
	 $("#error").css("display","none"); 
}
</script>
</body>
</html>